<template>
	<s-layout title="商品入库">
		<view class="cicon-notice"
		      style="padding: 10px;
	          margin: 5px;
	          width: 90%;
	          background-color: #F39800;
	          border-radius: 10px; color: #FFFFFF;">
			<text>海关分类选择,输入件数大于0即记录分类</text>
		</view>
		<uni-forms
				ref="addressFormRef"
				v-model="state.model"
				validateTrigger="bind"
				labelWidth="160"
				labelAlign="left"
				border
				:labelStyle="{ fontWeight: 'bold' }"
		>
			<view class="bg-white form-box ss-p-x-30">
				<uni-forms-item name="wareId" label="商品ID" class="form-item">
					<uni-easyinput
							v-model="state.model.wareId"
							placeholder="请填写商品ID"
							:inputBorder="false"
							placeholderStyle="color:#BBBBBB;font-size:30rpx;font-weight:400;line-height:normal"
					>
						<template #right>
							<button style="width: 120rpx; color: #FFFFFF; background: #459cff" class="ss-reset-button ui-Shadow-Main" @tap="onScanProductId">扫码</button>
						</template>
					</uni-easyinput>
				</uni-forms-item>
				<uni-forms-item name="mercariTrackNumber" label="物流单号" class="form-item">
					<uni-easyinput
							v-model="state.model.mercariTrackNumber"
							placeholder="请填写物流单号"
							:inputBorder="false"
							placeholderStyle="color:#BBBBBB;font-size:30rpx;font-weight:400;line-height:normal"
					>
						<template #right>
							<button style="width: 120rpx; color: #FFFFFF; background: #459cff" class="ss-reset-button ui-Shadow-Main" @tap="onScanTrackNumber">扫码</button>
						</template>
					</uni-easyinput>
				</uni-forms-item>

				<uni-forms-item name="wareType" label="海关分类" class="form-item">
					<radio-group @change="onRefundChange">
						<label
								class="ss-flex ss-col-center ss-p-y-10"
								v-for="(item, index) in state.model.wareTypeList"
								:key="index"
						>
							<radio
									:checked="state.model.wareType === item.value"
									color="var(--ui-BG-Main)"
									style="transform: scale(0.8)"
									:value="item.value"
							/>
							<view class="item-value ss-m-l-8">{{ item.text }}</view>
						</label>
					</radio-group>
					<text>{{ state.model.customsCategory }}</text>
				</uni-forms-item>

				<uni-forms-item
						name="storageImgUrl"
						label="拍摄图片"
						class="form-item"
				>
					<uni-file-picker
							@delete="e => onDelete(e)"
							ref="uploadStorage"
							v-model="state.model.pickerVal"
							fileMediatype="image"
							limit="1"
							:auto-upload="false"
							@select="e => onSelect(e)"
							>
					</uni-file-picker>
				</uni-forms-item>
				<uni-forms-item name="freightHeight" label="商品重量" class="form-item">
					<uni-easyinput
							v-model="state.model.freightHeight"
							placeholder="请填写商品重量"
							:inputBorder="false"
							placeholderStyle="color:#BBBBBB;font-size:30rpx;font-weight:400;line-height:normal"
					>
						<template #right>
							g
						</template>
					</uni-easyinput>
				</uni-forms-item>
			</view>
		</uni-forms>
		<su-popup :show="state.showTable" round="10" :showClose="true" @close="state.showTable = false">
			<view class="modal-box page_box">
				<view class="modal-head item-title head_box ss-flex ss-row-center ss-col-center"
				>填写分类</view
				>
				<view class="modal-content content_box">
					<view style="position: relative; margin-top: 3%">
						<uni-table ref="table" border emptyText="暂无更多数据" stripe>
							<uni-tr>
								<uni-th align="center" width="220rpx">名称</uni-th>
								<uni-th align="center" width="80rpx">数量</uni-th>
							</uni-tr>
							<uni-tr v-for="(item, index) in state.customData" :key="index">
								<uni-td>
									<uni-easyinput
											v-model="item.name"
											:inputBorder="false"
											disabled
									>
									</uni-easyinput>
								</uni-td>
								<uni-td>
									<uni-easyinput
											v-model="item.num"
											:inputBorder="false"
											placeholder="请填写申报商品单价"
											type="digit"
									>
										<template #right>
											件
										</template>
									</uni-easyinput>
								</uni-td>
							</uni-tr>
						</uni-table>
					</view>
				</view>
				<view class="modal-foot foot_box ss-flex ss-row-center ss-col-center">
					<button class="ss-reset-button close-btn ui-BG-Main-Gradient" @tap="onConfirmCategory"
					>确定</button
					>
				</view>
			</view>
		</su-popup>
		<view v-if="state.wareInfo.wareId" style="margin-top: 20rpx; padding: 20rpx">
			<text style="font-size: 35rpx; font-weight: bold;"> 日本价格：￥{{ state.wareInfo.price }} </text>
			<text style="font-size: 35rpx; font-weight: bold;"> 中国价格：￥{{ state.wareInfo.priceZh }} </text>
			<br>
			<text style="font-size: 35rpx; font-weight: bold;"> 仓库状态：{{ state.wareInfo.storageStatus === 1 ? '已入库' : '未入库' }} </text>
			<br>
			<text style="font-size: 35rpx; font-weight: bold;"> 入库时间：{{ state.wareInfo.inStorageTime }} </text>
			<br>
			<text style="font-size: 35rpx; font-weight: bold;"> 订单备注：{{ state.wareInfo.note }} </text>
			<br>
			<text style="font-size: 35rpx; font-weight: bold;"> 会员ID：{{ state.wareInfo.memberId }} </text>
			<br>
			<text style="font-size: 35rpx; font-weight: bold;"> 会员昵称：{{ state.wareInfo.memberUsername }} </text>
			<br>
		</view>
		<view v-if="state.wareInfo.warePics">
			<view v-for="(item,index) in state.wareInfo.warePics.split(',')">
				<su-image
						class="content-img"
						isPreview
						:previewList="state.wareInfo.warePics.split(',')"
						:current="index"
						:src="item"
						mode="aspectFit"
				></su-image>
			</view>
		</view>
		<view v-if="state.wareInfo.pic">
			<view v-for="(item,index) in state.wareInfo.pic.split(',')">
				<su-image
						class="content-img"
						isPreview
						:previewList="state.wareInfo.pic.split(',')"
						:current="index"
						:src="item"
						mode="aspectFit"
				></su-image>
			</view>
		</view>
		<su-fixed bottom :opacity="false" bg="" placeholder :noFixed="false" :index="10">
			<view class="footer-box ss-flex-col ss-row-between ss-p-20">
				<view class="ss-m-b-20" style="display: flex; justify-content: center">
					<!--<button style="width: 33.33%; color: #FFFFFF; background: #9028cf" class="ss-reset-button save-btn ui-Shadow-Main" @tap="onSendTransactionsReview">到货</button>-->
					<button style="width: 33.33%; color: #FFFFFF; background: #ff9945" class="ss-reset-button save-btn ui-Shadow-Main" @tap="onPrint">打印</button>
					<button style="width: 33.33%; color: #FFFFFF; background: #459cff" class="ss-reset-button save-btn ui-Shadow-Main" @tap="onSearch">查询</button>
					<button style="width: 33.33%; color: #FFFFFF; background: #00c94c" class="ss-reset-button save-btn ui-Shadow-Main" @tap="onSave">入库</button>
				</view>
			</view>
		</su-fixed>
		<su-dialog ref="suDialogRef"
		           :show="state.wareInfo.show"
		           title="货物详情"
		           @confirm="state.wareInfo.show = false"
		           @close="state.wareInfo.show = false">
			<view class="ss-flex-col ss-p-20">
				<text style="font-size: 45rpx; font-weight: bold; text-align: center">ID：{{ state.wareInfo.wareId }} </text>
				<image style="width: 500rpx; height: 500rpx" :src="sheep.$url.cdn(state.wareInfo.pic)" mode="aspectFill"></image>
			</view>
		</su-dialog>
		<view class="">
			<canvas canvas-id="mBarcode" :style="`width: ${state.print.canvasWidth}px; height: ${state.print.canvasHeight}px; z-index: -99`" />
		</view>
	</s-layout>
</template>

<script setup>
import {reactive, ref} from 'vue';
import sheep from '@/sheep';
import {onLoad} from '@dcloudio/uni-app';
// 引入baseUrl
import {baseUrl} from '@/sheep/config';

import {
	didReadPrintCountInfo,
	drawBarcode,
	drawText,
	endDrawLabel,
	startDrawLabel,
	startJob,
	print
} from "@/static/JCAPI/JCAPI";

const addressFormRef = ref(null);
const state = reactive({
	showRegion: false,
	showTable: false,
  printParamsBody: {},
	wareInfo: {
		show: false,
	},
	model: {
		wareId: '',
		orderId: '',
		customsCategory: '',
		mercariTrackNumber: '',
		wareType: undefined,
		storageImgUrl: '',
		storageImgUrlList: [],
		pickerVal: 0,
		freightHeight: 0.0,
		wareTypeList: [
			{
				text: '普通',
				value: 0,
			},
			{
				text: '组合',
				value: 1,
			}
		],
	},
	customData: [],
	currentRes: {},
	print: {
		canvasWidth: 200,
		canvasHeight: 200,
	}
});

const uploadStorage = ref(null);

function uniPrint(wareId, memberId, mark, inStorageTime, note) {
	console.log('uniPrint', wareId, memberId, mark, inStorageTime, note)
	//标签尺寸
	const labelWidth = 60
	const labelHeight = 40
	//B3S/B1/B21/B203/K3/K3W的mu tiple传8，B32/Z401/M2的mutiple传11.81
	const multiple = 8
	state.print.canvasWidth = labelWidth * multiple
	state.print.canvasHeight = labelHeight * multiple
	// 绘制条码
	let ctx = wx.createCanvasContext('mBarcode', this);
	ctx.setFillStyle('white');
	ctx.fillRect(0, 0, 200, 80);
	ctx.draw();
	ctx.setFillStyle('black');
	ctx.setFontSize(3);
	ctx.fillText('准备打印', 3, 20);
	ctx.draw();
	startDrawLabel('mBarcode', this, labelWidth, labelHeight)
	if (!sheep.$helper.isRealEmpty(state.printParamsBody.barcode)) {
    drawBarcode(wareId,
        state.printParamsBody.barcode.x,
        state.printParamsBody.barcode.y,
        state.printParamsBody.barcode.width,
        state.printParamsBody.barcode.height,
        state.printParamsBody.barcode.rotation,
        state.printParamsBody.barcode.fontSize,
        state.printParamsBody.barcode.fontHeight,
        state.printParamsBody.barcode.postion)
    drawText(`会员ID：${memberId}`,
        state.printParamsBody.textRow.x,
        state.printParamsBody.textRow.y,
        state.printParamsBody.textRow.fontHeight,
        state.printParamsBody.textRow.rotation)
    drawText(`团长ID：${mark}`,
        state.printParamsBody.textRow.x,
        state.printParamsBody.textRow.y + 4,
        state.printParamsBody.textRow.fontHeight,
        state.printParamsBody.textRow.rotation)
    drawText(`订单备注：${note}`,
        state.printParamsBody.textRow.x,
        state.printParamsBody.textRow.y + 4 * 2,
        state.printParamsBody.textRow.fontHeight,
        state.printParamsBody.textRow.rotation)
    drawText(`入库时间：${inStorageTime}`,
        state.printParamsBody.textRow.x,
        state.printParamsBody.textRow.y + 4 * 3,
        state.printParamsBody.textRow.fontHeight,
        state.printParamsBody.textRow.rotation)
  } else {
    // default print params
    drawBarcode(wareId, 8, 3, 45, 15, 0, 4, 4, 1)
    drawText(`会员ID：${memberId}`, 8, 16, 3, 0)
    drawText(`团长ID：${mark}`, 8, 20, 3, 0)
    drawText(`订单备注：${note}`, 8, 24, 3, 0)
    drawText(`入库时间：${inStorageTime}`, 8, 28, 3, 0)
  }

	endDrawLabel(() => {
		startJob(1, 3, 1,() => {
			print(1, (res) => {
				console.log(res)
			})
		})
	})

	didReadPrintCountInfo((res) => {
		console.log(res, '打印进度')
		if (res.count === 1) {
			uni.reLaunch({
				url: '/pages/app/sign',
			})
		}
	})
}

//选择售后类型
function onRefundChange(e) {

	state.model.wareType = e.detail.value;
	console.log(state.model.wareType, 'wareType')
	if (state.model.wareType == 1) {
		state.customData.forEach(item => {
			item.name = '组合-' + item.name
		})
		console.log(state.customData, 'customData')
	} else {
		state.customData.forEach(item => {
			item.name = item.name.replace('组合-', '')
		})
	}
	state.showTable = true
}

function onConfirmCategory() {
	console.log('保存分类')
	state.model.customsCategory = '';
	state.customData.forEach(item => {
		if (item.num > 0) {
			state.model.customsCategory += `${item.name}(${item.num}件),`
		}
	})
	if (sheep.$helper.isRealEmpty(state.model.customsCategory)) {
		sheep.$helper.toast('请填写海关分类');
		return;
	}
	state.model.customsCategory = state.model.customsCategory.substring(0, state.model.customsCategory.length -1)
	state.showTable = false
}

function onSelect(e) {
	console.log(e, 'select')
	console.log(state.model.storageImgUrlList, 'storageImgUrlList')
	const tempFilePaths = e.tempFilePaths
	state.model.storageImgUrlList.push(tempFilePaths[0])
}

function onDelete(e) {
	console.log(e, 'delete')
	console.log(state.model.storageImgUrlList, 'storageImgUrlList-delete-before')
	state.model.storageImgUrlList.splice(e.tempFilePath, 1)
	console.log(state.model.storageImgUrlList, 'storageImgUrlList-delete-after')
}

function onSendTransactionsReview() {
	if (sheep.$helper.isRealEmpty(state.model.orderId)) {
		sheep.$helper.toast('请先点击查询获取货物详情');
		return;
	}
	// 确认框
	uni.showModal({
		title: `煤炉收货评价`,
		content: `确认商品${state.model.wareId}已收货了么（不是空包裹）, 确认将会发起煤炉收货评价确认`,
		success: async function (res) {
			if (res.confirm) {
				sheep.$api.order.sendTransactionsReview({
					orderId: state.model.orderId
				}).then(res => {
					sheep.$helper.toast('到货评价成功')
				})
			}
		}
	});
}

function onPrint() {
	if (sheep.$helper.isRealEmpty(state.model.wareId)) {
		sheep.$helper.toast('请填写商品ID');
		return;
	}
	sheep.$api.order.inStorageSearch({
		wareId: state.model.wareId,
		mercariTrackNumber: state.model.mercariTrackNumber,
		wareType: state.model.wareType
	}).then(res => {
		if (!sheep.$helper.isRealEmpty(res)) {
			console.log(state.wareInfo, 'wareInfo')
			uniPrint(
					res.wareId,
					res.memberId,
					res.memberMark,
					res.inStorageTime,
					res.note
			)
		}
	})
}

function onSearch() {
	if (sheep.$helper.isRealEmpty(state.model.wareId) && sheep.$helper.isRealEmpty(state.model.mercariTrackNumber)) {
		sheep.$helper.toast('请填写商品ID/或物流单号');
		return;
	}
	sheep.$api.order.inStorageSearch({
		wareId: state.model.wareId,
		mercariTrackNumber: state.model.mercariTrackNumber,
		wareType: state.model.wareType
	}).then(res => {
		if (!sheep.$helper.isRealEmpty(res)) {
			state.wareInfo = res
			state.model.orderId = res.orderId
			state.model.wareId = res.wareId
			state.model.mercariTrackNumber = res.mercariTrackNumber
			state.wareInfo.show = true;
		}
	})
}

function onScanTrackNumber() {
	uni.scanCode({
		scanType: ['barCode'],
		success: function (res) {
			console.log('条码类型：' + res.scanType);
			console.log('条码内容：' + res.result);
			state.model.mercariTrackNumber = res.result
		}
	});
}

function onScanProductId() {
	uni.scanCode({
		scanType: ['barCode'],
		success: function (res) {
			console.log('条码类型：' + res.scanType);
			console.log('条码内容：' + res.result);
			state.model.wareId = res.result
		}
	});
}

async function uploadFiles(urls) {
	if (urls.length === 0) {
		return; // 所有文件上传完成，结束递归
	}

	const filePath = urls[0];

	try {
		const res = await uni.uploadFile({
			url: baseUrl + '/no-auth/oss/upload',
			filePath: filePath,
			name: 'file'
		});

		if (res.statusCode === 200) {
			let data = JSON.parse(res.data);
			if (!sheep.$helper.isRealEmpty(data.url)) {
				state.model.storageImgUrl += data.url + ',';
			} else {
				sheep.$helper.toast(`图片${i + 1}上传失败，请稍后重新拍摄`);
			}
		}

	} catch (error) {
		sheep.$helper.toast(`图片${i + 1}上传失败，请稍后重新拍摄`);
	}

	// 继续上传下一个文件
	await uploadFiles(urls.slice(1));
}

async function onSave() {
	uni.showLoading({
		title: '上传中...',
		mask: true
	});

	try {

		if (sheep.$helper.isRealEmpty(state.model.wareId) && sheep.$helper.isRealEmpty(state.model.mercariTrackNumber)) {
			sheep.$helper.toast('请填写商品ID/物流单号');
			return;
		}
		if (sheep.$helper.isRealEmpty(state.model.customsCategory)) {
			sheep.$helper.toast('请填写海关分类');
			return;
		}
		if (sheep.$helper.isRealEmpty(state.model.freightHeight)) {
			sheep.$helper.toast('请填写商品重量');
			return;
		}
		if (state.model.freightHeight <= 0) {
			sheep.$helper.toast('商品重量必须大于0g');
			return;
		}

		await uploadFiles(state.model.storageImgUrlList);

		uni.hideLoading();

		if (sheep.$helper.isRealEmpty(state.model.storageImgUrl)) {
			sheep.$helper.toast('请上传图片');
			return;
		}

		state.model.storageImgUrl = state.model.storageImgUrl.substring(0, state.model.storageImgUrl.length - 1);

		await sheep.$api.order.inStorage({
			wareId: state.model.wareId,
			mercariTrackNumber: state.model.mercariTrackNumber,
			wareType: state.model.wareType,
			customsCategory: state.model.customsCategory,
			storageImgUrl: state.model.storageImgUrl,
			freightHeight: state.model.freightHeight,
		}).then(res => {
			state.currentRes = res;
			let content = ""
			if (!sheep.$helper.isRealEmpty(res.memberId) && res.status === 1) {
				content = `入库成功(●'◡'●) | 会员ID: ${res.memberId} | 订单备注: ${res.note} | 平台备注: ${res.merchantNote}`;
			} else {
				content = `入库失败ಠ_ಠ | 请重新尝试，多次失败请联系管理员~`;
			}
			// 确认框
			uni.showModal({
				title: '提示',
				content: content,
				showCancel: true,
				cancelText: '继续入库',
				confirmText: '打印条码',
				success: function (res) {
					if (res.confirm) {
						uniPrint(
								state.currentRes.wareId,
								state.currentRes.memberId,
								state.currentRes.memberMark,
								state.currentRes.inStorageTime,
                state.currentRes.note
						)
					} else {
						uni.reLaunch({
							url: '/pages/app/sign',
						})
					}
				}
			});
		})
	} catch (error) {
		uni.hideLoading();
		console.error(error);
	}
}

onLoad(async (options) => {
  let printParams = await sheep.$api.order.channelList({ type: 'print_params' });
  let dict = printParams[0];
  let printParamsBody = dict.dictValue;
  if (!sheep.$helper.isRealEmpty(printParamsBody)) {
    state.printParamsBody = JSON.parse(printParamsBody);
  }
	// 根据字典初始化数据结构
	let customDictList = await sheep.$api.order.channelList({ type: 'customs_category' });
	customDictList.forEach(item => {
		let obj = {
			name: item.dictValue,
			num: 0,
			checked: false,
		}
		state.customData.push(obj)
	})
});
</script>

<style lang="scss" scoped>
:deep() {
	.uni-forms-item__label .label-text {
		font-size: 28rpx !important;
		color: #333333 !important;
		line-height: normal !important;
	}

	.uni-easyinput__content-input {
		font-size: 28rpx !important;
		color: #333333 !important;
		line-height: normal !important;
		padding-left: 0 !important;
	}

	.uni-easyinput__content-textarea {
		font-size: 28rpx !important;
		color: #333333 !important;
		line-height: normal !important;
		margin-top: 8rpx !important;
	}

	.uni-icons {
		font-size: 40rpx !important;
	}

	.is-textarea-icon {
		margin-top: 22rpx;
	}

	.is-disabled {
		color: #333333;
	}
}

.default-box {
	width: 100%;
	box-sizing: border-box;
	height: 100rpx;

	.default-box-title {
		font-size: 28rpx;
		color: #333333;
		line-height: normal;
	}
}

.footer-box {
	.save-btn {
		width: 710rpx;
		height: 80rpx;
		border-radius: 40rpx;
		background: linear-gradient(90deg, var(--ui-BG-Main), var(--ui-BG-Main-gradient));
		color: $white;
	}

	.cancel-btn {
		width: 710rpx;
		height: 80rpx;
		border-radius: 40rpx;
		background: var(--ui-BG);
	}
}

.modal-box {
	width: 750rpx;
	// height: 680rpx;
	border-radius: 30rpx 30rpx 0 0;
	background: #fff;

	.modal-head {
		height: 100rpx;
		font-size: 30rpx;
	}

	.modal-content {
		font-size: 28rpx;
	}

	.modal-foot {
		.close-btn {
			width: 710rpx;
			line-height: 80rpx;
			border-radius: 40rpx;
			color: rgba(#fff, 0.9);
		}
	}
}

.canvas{
	position:fixed;
	/* display: none; */
	left: 100%;
}
</style>
